<template>
  <div class="inspectdemo-box">
    <div class="item-title">
      <div>每日施工检查</div>
      <!-- <el-button type="primary" @click="clckInsyuhu">检查内容</el-button> -->
      <el-button type="primary" @click="clckInspection">检查内容</el-button>
      <el-button type="primary" @click="clckViolation" v-if="qualified != '1'">上报违规</el-button>
      <el-button type="primary" @click="clckabnormal" v-if="qualified != '1'">上报异常</el-button>
    </div>
    <!-- 检查内容 -->
    <el-row v-show="Inspectionshow">
      <el-row style="font-weight: bold; width: 100%">检查内容</el-row>
      <el-row class="disflex" style="width: 100%; margin-top: 10px">
        <div class="disflex" style="width: 7%">检查内容：</div>
        <el-input type="textarea" style="width: 60%" :rows="2" placeholder="" v-model="formContent.examContent"
          maxlength="300" show-word-limit>
        </el-input>

        <div style="margin-left: 20px">
          检查结果：
          <el-radio-group v-model="qualified">
            <el-radio label="1" size="large">合格</el-radio>
            <el-radio label="2" size="large">不合格</el-radio>
          </el-radio-group>
        </div>
      </el-row>
      <el-row class="disflex" style="width: 100%; margin-top: 10px">
        <div class="disflex" style="width: 7%">现场拍照：</div>
        <el-upload v-model:file-list="fileList" class="upload-demo" accept=".png, .jpg, .jpeg"
          :on-success="handlerUploadSuccess" :on-remove="handleRemove" :on-preview="previewHandle"
          :action="baseUrlConfig.businessBaseUrl + '/fast/uploadFile'" multiple :limit="10">
          <!-- <el-button type="primary">Click to upload</el-button> -->
          <button>选择文件</button>&nbsp;&nbsp;
          <template #tip>
            <span>未选择任何文件</span>
          </template>
        </el-upload>
      </el-row>
    </el-row>
    <!-- 上报违规 -->
    <div v-show="Violationshow">
      <!-- <el-button type="primary" @click="clckInsyuhu">添加违规信息</el-button> -->
      <el-row v-for="(item, index) in formContent.violations" :key="index" style="margin-top: 10px">
        <el-row style="font-weight: bold; width: 100%;display: flex;align-items: center;margin-bottom: 10px;">
          <span>违规情况{{ index + 1 }}</span>
          <el-icon :size="20" color="#F56C6C" class="del-icon"
            v-if="formContent.violations && formContent.violations.length > 1" @click="removeItem(1, index)">
            <Remove />
          </el-icon>
        </el-row>
        <el-row class="disflex" style="width: 100%; margin-top: 10px">
          <div class="disflex" style="width: 7%">违规情况描述：</div>
          <el-input type="textarea" style="width: 60%" :rows="2" placeholder="" v-model="item.description" maxlength="300"
            show-word-limit>
          </el-input>
        </el-row>
        <el-row class="disflex" style="width: 100%; margin-top: 10px">
          <div class="disflex" style="width: 7%">现场拍照：</div>
          <el-upload v-model:file-list="item.fileList" class="upload-demo" accept=".png, .jpg, .jpeg"
            :on-success="handlerUploadSuccesstwo" :on-remove="handleRemovetwo"
            :action="baseUrlConfig.businessBaseUrl + '/fast/uploadFile'" multiple :limit="10">
            <!-- <el-button type="primary">Click to upload</el-button> -->
            <button>选择文件</button>&nbsp;&nbsp;
            <template #tip>
              <span>未选择任何文件</span>
            </template>
          </el-upload>
        </el-row>
      </el-row>
      <div class="add-item">
        <el-button plain :icon="Plus" type="primary" style="background: none;width: 200px;color: #409EFF"
          @click="addItem(1)">添加</el-button>
      </div>
    </div>
    <!-- 上报异常 -->
    <div v-show="abnormalshow">
      <el-row v-for="(item, index) in formContent.abnormalities" :key="index" style="margin-top: 10px;">
        <el-row style="font-weight: bold; width: 100%;display: flex;align-items: center;margin-bottom: 10px;">
          <span>异常情况{{ index + 1 }}</span>
          <el-icon :size="20" color="#F56C6C" class="del-icon"
            v-if="formContent.abnormalities && formContent.abnormalities.length > 1" @click="removeItem(2, index)">
            <Remove />
          </el-icon>
        </el-row>
        <el-row class="disflex" style="width: 100%; margin-top: 10px">
          <div class="disflex" style="width: 7%">异常情况描述:</div>
          <el-input type="textarea" style="width: 60%" :rows="2" placeholder="" v-model="item.description" maxlength="300"
            show-word-limit>
          </el-input>
        </el-row>
        <el-row class="disflex" style="width: 100%; margin-top: 10px">
          <div class="disflex" style="width: 7%">现场拍照：</div>
          <el-upload v-model:file-list="item.fileList" class="upload-demo" accept=".png, .jpg, .jpeg"
            :on-success="handlerUploadSuccesswhere" :on-remove="handleRemovewhere"
            :action="baseUrlConfig.businessBaseUrl + '/fast/uploadFile'" multiple :limit="10">
            <!-- <el-button type="primary">Click to upload</el-button> -->
            <button>选择文件</button>&nbsp;&nbsp;
            <template #tip>
              <span>未选择任何文件</span>
            </template>
          </el-upload>
        </el-row>
      </el-row>
      <div class="add-item">
        <el-button plain :icon="Plus" type="primary" style="background: none;width: 200px;color: #409EFF"
          @click="addItem(2)">添加</el-button>
      </div>
    </div>
    <!-- 视频监控 -->
    <el-row style="margin-top: 30px">
      <videoMonitoring />
    </el-row>
    <!-- 按钮 -->
    <el-row style="margin-top: 12px">
      <el-col :span="12"> </el-col>
      <el-button plain @click="goDetails">取消</el-button>
      <el-button plain @click="cacheSave">保存</el-button>
      <el-button plain @click="submitto">提交</el-button>
    </el-row>
    <div>
      <el-image-viewer hide-on-click-modal @close="() => { showViewer = false }" v-if="showViewer" :url-list="[previewUrl]" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { supervisoryFormappendyu } from "@/api/construction/projectSupervise";
import videoMonitoring from "@/views/construction/project-supervise/components/videoMonitoring/index.vue";
import { computed, reactive, ref, onBeforeMount, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import { baseUrlConfig } from '@/config/config'

import type { UploadProps, UploadUserFile } from "element-plus";
import router from "@/router";
import { useRoute } from "vue-router";
import { useStore } from "vuex";
interface FileFace {
  enclosureContent: string;
  enclosureName: string;
  enclosureSuffix: string;
  resourceAddress: string;
  enclosureCode: string;
}
const Inspectionshow = ref(true); //检查内容
const Violationshow = ref(false); //违规
const abnormalshow = ref(false); //异常
const fileList = ref<UploadUserFile[]>([]);
const store = useStore();
const route = useRoute();
const userInfo = computed(() => store.state.user.userInfo);
let formContent = reactive({
  examContent: "", //检查内容
  situation: [], //现场照片
  violations: [{ description: "", videoOrPics: [], fileList: [] }], //违规情况
  abnormalities: [{ description: "", videoOrPics: [], fileList: [] }], //异常情况
}); //新增施工监管单
// const beforeUpload = (rawFile) => {
//   emits("beforeUpload", rawFile);
// };

let qualified = ref("")

watch(qualified, (val: string) => {
  if(val == '1') {
    formContent.violations = [{ description: "", videoOrPics: [], fileList: [] }]
    formContent.abnormalities = [{ description: "", videoOrPics: [], fileList: [] }]
  }
})

let previewUrl = ref<string>('')
const showViewer = ref<boolean>()
const previewHandle: UploadProps['onPreview'] = (file) => {
  let url: string = file.url ? file.url : (file.response as any).data.resourceAddress
  previewUrl.value = url;
  showViewer.value = true
}

onBeforeMount(() => {
  let cache = localStorage.getItem('supervisorData') || "{}"
  let cacheData = JSON.parse(cache)
  if (cacheData[route.query.id as any]) {
    formContent = reactive(cacheData[route.query.id as any].formContent)
    qualified.value = cacheData[route.query.id as any].qualified
    fileList.value = formContent.situation
  }
})

const addItem = (type: number) => {
  if (type === 1) {
    formContent.violations.push({ description: "", videoOrPics: [], fileList: [] })
  } else {
    formContent.abnormalities.push({ description: "", videoOrPics: [], fileList: [] })
  }
}

const removeItem = (type: number, index: number) => {
  if (type === 1) {
    formContent.violations.splice(index, 1)
  } else {
    formContent.abnormalities.splice(index, 1)
  }
}

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (!!(rawFile.type.indexOf("image") == -1)) {
    ElMessage.error("图片格式不正确");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("上传大小不能超过 10MB!");
    return false;
  }
  return true;
};
// 上传成功
const handlerUploadSuccess: UploadProps["onSuccess"] = (
  resp,
  uploadFile,
  uploadFiles
) => {
  if (resp.code === "1") {
    formContent.situation.push({
      name: uploadFile.name,
      type: resp.data.storageType,
      url: resp.data.resourceAddress,
      enclosureCode: resp.data.enclosureCode,
    });
  }
};
//移除文件
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  const code = uploadFile.response.data.enclosureCode;
  const values: Array<any> = [];
  formContent.situation.forEach((item, index) => {
    if (item.enclosureCode !== code) {
      values.push(item);
    }
  });
  formContent.situation = values;
};
// 违规上传成功
const handlerUploadSuccesstwo: UploadProps["onSuccess"] = (
  resp,
  uploadFile,
  uploadFiles
) => {
  if (resp.code === "1") {
    formContent.violations[0].videoOrPics.push({
      name: uploadFile.name,
      type: resp.data.storageType,
      url: resp.data.resourceAddress,
      enclosureCode: resp.data.enclosureCode,
    });
  }
};
//移除文件
const handleRemovetwo: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  const code = uploadFile.response.data.enclosureCode;
  const values: Array<any> = [];
  formContent.violations[0].videoOrPics.forEach((item, index) => {
    if (item.enclosureCode !== code) {
      values.push(item);
    }
  });
  formContent.violations[0].videoOrPics = values;
};
// 违规上传成功
const handlerUploadSuccesswhere: UploadProps["onSuccess"] = (
  resp,
  uploadFile,
  uploadFiles
) => {
  if (resp.code === "1") {
    formContent.abnormalities[0].videoOrPics.push({
      name: uploadFile.name,
      type: resp.data.storageType,
      url: resp.data.resourceAddress,
      enclosureCode: resp.data.enclosureCode,
    });
  }
};
//移除文件
const handleRemovewhere: UploadProps["onRemove"] = (
  uploadFile,
  uploadFiles
) => {
  const code = uploadFile.response.data.enclosureCode;
  const values: Array<any> = [];
  formContent.abnormalities[0].videoOrPics.forEach((item, index) => {
    if (item.enclosureCode !== code) {
      values.push(item);
    }
  });
  formContent.abnormalities[0].videoOrPics = values;
};
//返回
const goDetails = () => {
  router.push("/construction/project-supervise");
};
//新增施工监管单
const submitto = async () => {
  // id: userInfo.value.userId,
  //     name: userInfo.value.name,
  //     organId: userInfo.value.organId,
  //     organName: userInfo.value.organName
  if(qualified.value == '1') {
    if(!formContent.examContent) {
      return ElMessage.warning("请填写检查内容")
    }
  }else if(qualified.value == '2') {
    if(!(formContent.violations[0].description || formContent.abnormalities[0].description)) {
      return ElMessage.warning("请填写违规情况或异常情况")
    }
  }

  const payload: any = {
    // createTime: new Date(),
    creator: {
      id: userInfo.value.userId,
      name: userInfo.value.name,
      organId: userInfo.value.organId,
      organName: userInfo.value.organName,
    },
    formContent: formContent,
    supervisionId: route.query.id,
  };
  supervisoryFormappendyu(payload)
    .then((res) => {
      if (res.code == "1") {
        clearCahe()
        ElMessage.success("上传成功");
        goDetails();
      }
    })
    .catch((err) => {
      console.log("err", err);
    });
  // supervisoryFormappendyu(payload).then((res) => {
  // console.log("res-------", res);
  // });
};
//点击检查内容
const clckInsyuhu = () => {
  console.log("打印----", formContent);
};
//点击检查内容
const clckInspection = () => {
  Inspectionshow.value = true;
  Violationshow.value = false;
  abnormalshow.value = false;
};
//点击违规
const clckViolation = () => {
  Inspectionshow.value = false;
  Violationshow.value = true;
  abnormalshow.value = false;
};
//点击异常
const clckabnormal = () => {
  Inspectionshow.value = false;
  Violationshow.value = false;
  abnormalshow.value = true;
};

const cacheSave = () => {
  let cData = localStorage.getItem("supervisorData") || "{}"
  let obj = JSON.parse(cData)
  obj[route.query.id as any] = {formContent, qualified: qualified.value}
  localStorage.setItem("supervisorData", JSON.stringify(obj))
  ElMessage.success("保存成功")
}

const clearCahe = () => {
  let cData = localStorage.getItem("supervisorData") || "{}"
  let obj = JSON.parse(cData)
  if (obj[route.query.id as any]) {
    console.log('--------------')
    delete obj[route.query.id as any]
    localStorage.setItem("supervisorData", JSON.stringify(obj))
  }
}

defineExpose({});
</script>

<style lang="less" scoped>
.inspectdemo-box {
  margin: 12px;
  padding: 24px;
  border-radius: 8px;
  background: #fff;
  .item-title {
    display: flex;
    align-items: center;
    padding: 10px;
    font-size: 16px;
    font-weight: bold;
    color: #353a42;
    line-height: 24px;
    margin-bottom: 20px;
    border-bottom: 1px solid rgb(0 0 0 / 11.9%);
    &>div {
      margin-right: 5px;
    }
  }
  .del-icon {
    margin-left: 20px;
    cursor: pointer;
  }
  .add-item {
    margin-left: 7%;
  }
}
.disflexend {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}</style>
